
package com.v1.video.option.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.v1.video.activity.SettingRecommendAppActivity;
import com.v1.video.domain.RecommendAppInfo;
import com.v1.video.domain.RecommendInfoApp;
import com.v1.video.option.db.RecommendAppDbUtil;
import com.v1.video.util.Logger;
import com.v1.video.util.StringUtil;

public class DownloadAppUtil {
    // 下载文件保存目录
    public static final String DOWNLOADDIR = Environment.getExternalStorageDirectory().getPath()
            + "/V1/Video/apk";

    private static final String TAG = "DownloadAppUtil";

    public static Handler outerHandler = null;

    // public static HashMap<String, DownloadInfo> downloadList = new
    // HashMap<String, DownloadInfo>();
//    public static List<RecommendAppInfo> downloadList = new ArrayList<RecommendAppInfo>();
    public static HashMap<String, RecommendAppInfo> downloadList = new HashMap<String, RecommendAppInfo>();
    static Context context = null;

    // public static AdminDownedAdapter downedAdapter = null;
    // public static AdminDownningAdapter downningAdapter = null;

    // public static NotificationManager updateNotificationManager = null;

    public static final int STATE_START = 0;// 开始下载

    public static final int STATE_DOING = 1;// 下载中

    public static final int STATE_SUCC = 2;// 下载成功

    public static final int STATE_FAIL = 3;// 下载失败
    public static final int STATE_FAIL_NET = 4;// 下载失败（联网问题）

    public static final int STATE_FAIL_NET_SET = 9;// 非指定网络(即：不在指定的网络下，则不下载，返回消息)

    public static final int STATE_FAIL_STORE = 5;// 下载失败（内存问题）

    public static final int STATE_FAIL_NULL = 6;// 下载失败（服务器无数据问题）

    public static final int STATE_FAIL_OTHER = 7;// 下载失败（其他问题）

    public static final int STATE_OVER = 8;// 下载结束了

    // 下载状态
    private static int count = 0;

    public static class DownAppRunnable implements Runnable {
        RecommendAppInfo mEntity = null;

        Context mContext = null;

        Message message;

        public boolean isStop = false;
        
        public int pos = 0;

        public DownAppRunnable(Context context, RecommendAppInfo entity,int pos) {
            mEntity = entity;
            mContext = context;
            message = updateHandler.obtainMessage();
            this.pos = pos;
        }

        /**
		 * 
		 */
        public void run() {
            // //
            // Bundle data = new Bundle();
            // data.putString("fileId", mEntity.fileId);
            // message.what = STATE_START;
            // message.setData(data);
            // updateHandler.sendMessage(message);
            downloadFile();
            //
            // sendToOuterHandler(mEntity, false);
            // updateHandler.sendMessage(message);
        }

        /**
         * 下载文件
         * 
         * @return
         */
        public boolean downloadFile() {
            boolean result = false;

            HttpURLConnection httpConnection = null;
            InputStream is = null;
            FileOutputStream fos = null;

            try {
                if (mEntity.saveFilePath.equals("")) {
                    message = updateHandler.obtainMessage();
                    message.what = STATE_FAIL;
                    message.obj = mEntity;
                    updateHandler.sendMessage(message);
                    return false;
                }
                File dir = new File(DOWNLOADDIR);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                File file = new File(mEntity.saveFilePath);
                // Logger.i(TAG, "mEntity.saveFilePath==" +
                // mEntity.saveFilePath);
                // Logger.i(TAG, "mEntity.fileLinkurl==" + mEntity.fileLinkurl);
                if (!file.exists())
                    file.createNewFile();
                
                mEntity.currSize = file.length();
                // ///////////////////////////////////////////////
                // /获取下载文件大小-开始
                // //////////////////////////////////////////////
                if (mEntity.totalSize <= 0) {
                    // Logger.i(TAG, "mEntity.totalSize =0 下来获取其大小");
                    String urlStr = StringUtil.StrTrim(mEntity.appUrl);
                    if (!"".equals(urlStr)) {
                        URL l = new URL(urlStr);
                        HttpURLConnection c = (HttpURLConnection) l.openConnection();
                        if (HttpURLConnection.HTTP_OK == c.getResponseCode()) {
                            // 根据响应获取文件大小
                            mEntity.totalSize = c.getContentLength();
                            // Logger.i(TAG, "获取视频大小mEntity.totalSize =" +
                            // mEntity.totalSize);
                            // InputStream s = c.getInputStream();
                            // byte[] b = new byte[20];
                            // int len = s.read(b);
                            // s.close();
                            // String ll = new String(b, 0, len);
                            // mEntity.totalSize = Long.parseLong(ll.trim());
                            if (mEntity.totalSize <= 0) {
                                // handler回传表明数据为空，条数-1,下载下一条，删除数据库;
                                message = updateHandler.obtainMessage();
                                message.what = STATE_FAIL_NULL;
                                message.obj = mEntity;
                                updateHandler.sendMessage(message);
                                return false;
                            }else{
//                                RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                            }
                            // 记录到数据库
                            // updateDBDownloadTask(mEntity);//ft_5.6目前考虑，下载不用存储数据库

//                            Logger.i(TAG, "mEntity.totalSize mEntity.fileLinkurl:"
//                                    + mEntity.totalSize + "  " + mEntity.appUrl);
                        }
                        if (c != null) {
                            c.disconnect();
                        }
                    }
                }
//                Logger.i(TAG, "mEntity.totalSize = " + mEntity.totalSize);
                // sendToOuterHandler(mEntity, false);
                // ///////////////////////////////////////////////
                // /获取下载文件大小-结束
                // //////////////////////////////////////////////

                if (mEntity.totalSize > 0 && mEntity.currSize >= mEntity.totalSize) {
                    mEntity.progress = 100;
                    mEntity.status = RecommendAppInfo.STATUS_DOWNED;
//                    RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                    // updateDBDownloadTask(mEntity);//ft_5.6目前考虑，下载不用存储数据库

                    message = updateHandler.obtainMessage();
                    message.what = STATE_SUCC;
                    message.obj = mEntity;
                    updateHandler.sendMessage(message);
                    
                    if (outerHandler != null) {
                        Message message = outerHandler.obtainMessage();
                        message.what = RecommendAppInfo.STATUS_DOWNED;
                        message.arg1 = pos;
                        sendToOuterHandler(message);
                    }
                    return true;
                }
                
                Logger.i(TAG, "下面开始下载 ");
                String urlStr = StringUtil.StrTrim(mEntity.appUrl);
                URL url = new URL(urlStr);
                httpConnection = (HttpURLConnection) url.openConnection();
                httpConnection.setConnectTimeout(200000);
                httpConnection.setReadTimeout(200000);
                httpConnection.setRequestProperty("Connection", "Keep-Alive");

                if (mEntity.totalSize > 0) {
                    // 注意：暂时不采用断点续传，考虑到版本问题（这里放开是proper需要断点续传）
                    // String range = "bytes=" + currentSize ;
                    String range = "bytes=" + mEntity.currSize + "-" + (mEntity.totalSize);
                    // //@////@System.out.println("range:" + range);
                    httpConnection.setRequestProperty("RANGE", range);
                }
                //
                int ret = httpConnection.getResponseCode();
                // Map<String, List<String>> headers = c.getHeaderFields();
                // for (String name : headers.keySet()) {
                // if (name != null)
                // //@////@System.out.println("name:" + name);
                // }
                if (ret == HttpURLConnection.HTTP_OK || ret == HttpURLConnection.HTTP_PARTIAL) {
                    Logger.i(TAG, "获取到响应码==" + ret);
                    is = httpConnection.getInputStream();
                    // 206断点续传
                    fos = new FileOutputStream(file, ret == HttpURLConnection.HTTP_PARTIAL ? true
                            : false);
                    int bufflen = (int) mEntity.totalSize / 10;
                    byte buffer[] = new byte[bufflen];
                    int readsize = 0;
                    int progress = (int) (mEntity.currSize * 100 / mEntity.totalSize);
                    int progress2 = progress;
                    if (outerHandler != null) {
                        Message message = outerHandler.obtainMessage();
                        message.arg1 = pos;
                        message.arg2 = progress;
                        message.what = RecommendAppInfo.STATUS_DOWNNING;
                        sendToOuterHandler(message);
                    }
                    // ///////////////////////////////////////
                    // 初始化消息栏的百分比
                    // ///////////////////////////////////////
                    // int progress = (int) (mEntity.currSize * 100 /
                    // mEntity.totalSize);
                    // mEntity.progress = progress >= 100 ? 100 : progress;
                    // ///////////////////////////////////////
                    // ///////////////////////////////////////
                    // ///////////////////////////////////////
                    // sendToOuterHandler(mEntity, false);
                    mEntity.status = RecommendAppInfo.STATUS_DOWNNING;
//                    RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                    while ((readsize = is.read(buffer)) > 0) {
                        if (mEntity.status == RecommendAppInfo.STATUS_DELETE) {
                            isStop = true;
                            break;
                        }
                        if (isStop) {
                            mEntity.status = RecommendAppInfo.STATUS_STOP;
                            Logger.i(TAG, "保存时mEntity.progress=="+mEntity.progress);
//                            RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                            if (outerHandler != null) {
                                Message message = outerHandler.obtainMessage();
                                message.what = RecommendAppInfo.STATUS_STOP;
                                message.arg1 = pos;
                                sendToOuterHandler(message);
                            }
                            break;
                        }
                        // Logger.i(TAG, "正在下载ing_"+readsize);

                        mEntity.status = RecommendAppInfo.STATUS_DOWNNING;
                        fos.write(buffer, 0, readsize);
                        mEntity.currSize += readsize;
                        
                        progress = (int) (mEntity.currSize * 100 / mEntity.totalSize);
                        if(progress < mEntity.progress){
                            progress = mEntity.progress;
                        }
//                        if (mEntity.progress != progress && progress <= 100) {
//                            mEntity.progress = progress >= 100 ? 100 : progress;                            
//                        }
                        mEntity.progress = progress >= 100 ? 100 : progress; 
                        Logger.i(TAG, mEntity.getPackageName()+"的progress=="+progress);
                        if (outerHandler != null) {
                            if(progress2 != progress){
                                progress2 = progress;
                                Message message = outerHandler.obtainMessage();
                                message.arg1 = pos;
                                message.arg2 = progress;
                                message.what = RecommendAppInfo.STATUS_DOWNNING;
                                sendToOuterHandler(message);
                            }
                        }else{
                            Logger.i(TAG, "outerHandler == null");
                        }
                        // // // 为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                        // // if ((mEntity.progress % 10) == 0) {
                        // // mEntity.updateNotification.contentView
                        // // .setTextViewText(
                        // // R.id.notificationPercent,
                        // // mEntity.progress + "%");
                        // // mEntity.updateNotification.contentView
                        // // .setProgressBar(
                        // // R.id.notificationProgress, 100,
                        // // mEntity.progress, false);
                        // // updateNotificationManager.notify(mEntity.id,
                        // // mEntity.updateNotification);
                        // // }
                        // //
                        // sendToOuterHandler(mEntity, true);
                        // }
                    }
                    if (!isStop) {
                        mEntity.status = RecommendAppInfo.STATUS_DOWNED;
//                        RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                        // //保存到数据库
                        // updateDBDownloadTask(mEntity);//ft_5.6目前考虑，下载不用存储数据库

                        message = updateHandler.obtainMessage();
                        message.what = STATE_SUCC;
                        message.obj = mEntity;
                        updateHandler.sendMessage(message);
                        if (outerHandler != null) {
                            Message message = outerHandler.obtainMessage();
                            message.what = RecommendAppInfo.STATUS_DOWNED;
                            message.arg1 = pos;
                            sendToOuterHandler(message);
                        }
                        return true;
                    }

                    buffer = null;
                } else {
                    Logger.i(TAG, "获取响应码有问题=" + ret);
                    mEntity.status = RecommendAppInfo.STATUS_STOP;
//                    RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                    message = updateHandler.obtainMessage();
                    message.what = STATE_FAIL;
                    message.obj = mEntity;
                    updateHandler.sendMessage(message);
                    if (outerHandler != null) {
                        Message message = outerHandler.obtainMessage();
                        message.arg1 = pos;
                        message.arg2 = mEntity.progress;
                        message.what = RecommendAppInfo.STATUS_STOP;
                        sendToOuterHandler(message);
                    }
                }
            } catch (Exception ex) {
                Logger.i(TAG, "爆异常了");
//                mEntity.status = RecommendAppInfo.STATUS_FAILED;
                mEntity.status = RecommendAppInfo.STATUS_STOP;
//                RecommendAppDbUtil.addAppInfo(mContext, mEntity);//ft_12.4**********
                message = updateHandler.obtainMessage();
                message.what = STATE_FAIL;
                message.obj = mEntity;
                updateHandler.sendMessage(message);
                if (outerHandler != null) {
                    Message message = outerHandler.obtainMessage();
                    message.arg1 = pos;
                    message.arg2 = mEntity.progress;
                    message.what = RecommendAppInfo.STATUS_STOP;
                    sendToOuterHandler(message);
                }
                if (ex != null)
                    ex.printStackTrace();
            } finally {
                if (httpConnection != null) {
                    httpConnection.disconnect();
                }

                try {
                    if (is != null)
                        is.close();
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // //保存到数据库
            // updateDBDownloadTask(mEntity);
            // downloadList.put(mEntity.fileId, mEntity);
            //
            // sendToOuterHandler(mEntity, false);
            return result;
        }
    }

    /**
     * 
     */
    static Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            RecommendAppInfo entity = null;
            String key = null;
            try {
                entity = (RecommendAppInfo) msg.obj;
                key = entity.packageName;
                // Logger.i(TAG, "bundle==null_key==" + key);
                if (msg.what == STATE_DOING) {

                } else if (msg.what == STATE_SUCC) {// 开启下一条，更新数据库
                    // 下载成功 去安装
                	SettingRecommendAppActivity.isCanRefresh = true;
                    installApk(context,entity.saveFilePath);
                    
                } else if (msg.what == STATE_FAIL_NULL) {
                    // 下载失败
                } else if (msg.what == STATE_FAIL) {
                    // 下载失败
                }
            } catch (Exception e) {
                Logger.i(TAG, "handler爆异常了");
                e.printStackTrace();
            }
        }
    };

    // private static void sendToOuterHandler(DownloadInfo entity, boolean
    // isProgress) {
    // sendToOuterHandler(entity, isProgress, false);
    // }

    private static void sendToOuterHandler(int what) {
        if (outerHandler != null) {
            Message message = outerHandler.obtainMessage();
            message.what = what;
            outerHandler.sendMessage(message);
        }
    }

    private static void sendToOuterHandler(Message message) {
        if (outerHandler != null) {
            outerHandler.sendMessage(message);
        }
    }

    // private static void sendToOuterHandler(DownloadInfo entity, boolean
    // isProgress, boolean isDownSuccess) {
    // if (outerHandler != null || entity.mHandler != null) {
    // Bundle data = new Bundle();
    // data.putString("fileId", entity.fileId);
    // if(isDownSuccess){
    // data.putString("downSuccess", "1");
    // }
    //
    // if (outerHandler != null) {
    // Message message = outerHandler.obtainMessage();
    // message.setData(data);
    // outerHandler.sendMessage(message);
    // }
    // // if (entity.mHandler != null && !isProgress) {
    // // Message message = entity.mHandler.obtainMessage();
    // // message.setData(data);
    // // entity.mHandler.sendMessage(message);
    // // }
    // }
    // }

//    /**
//     * 载入下载记录
//     * 
//     * @param context
//     */
//    public static void initDownloadList(Context context) {
//        // TODO 载入下载记录
//        ArrayList<ZeroVideoInfo> listVideoInfo = ZeroVideoDBUtil.getVideoInfo(context);
//        int index = 0;
//        try {
//            do {
//
//                ZeroVideoInfo videoInfo = (ZeroVideoInfo) listVideoInfo.get(index);
//                DownloadInfo downloadInfo = new DownloadInfo(videoInfo);
//                downloadInfo.status = videoInfo.state;
//                downloadInfo.saveFilePath = videoInfo.videoFilePath;
//                downloadInfo.totalSize = videoInfo.totalsize;
//                downloadInfo.currSize = videoInfo.curSize;
//
//                // if(downloadInfo.status == downloadInfo.STATUS_DOWNNING){
//                // if(downloadList.containsKey(downloadInfo.fileId)){
//                // downloadInfo.runnable =
//                // downloadList.get(downloadInfo.fileId).runnable;
//                // }
//                //
//                // //重新开始下载
//                // if (downloadInfo.runnable != null) {
//                // downloadInfo.runnable.isStop = true;
//                // }
//                // downloadInfo.runnable = new DownRunnable(context,
//                // downloadInfo);
//                // Thread thread = new Thread(downloadInfo.runnable);
//                // thread.start();
//                // }
//                //
//                // downloadList.put(downloadInfo.fileId, downloadInfo);
//                index++;
//            } while (index < listVideoInfo.size());
//
//        } finally {
//
//        }
//    }

    public static void clearDownloadList() {
        // Set<String> keys = downloadList.keySet();
        // for (Object key : keys.toArray()) {
        // downloadList.remove(key);
        // }
        downloadList.clear();
    }

    /**
     * 增加下载任务
     * 
     * @param newsinfo
     * @return
     */
    public static boolean addDownloadTask(Context context, RecommendAppInfo info) {
        if (info == null || isRepeatDownload(info))
            return false;
        boolean result = false;
        if (DownloadAppUtil.context == null) {
            DownloadAppUtil.context = context;
        }
        try {
//            DownloadAppUtil di = new DownloadAppUtil(videoInfo);

            // String sql
            // =String.format("insert into downloadtask(status,totalsize,thumburl,filelinkurl,filename,"
            // +
            // "fileid,duration) values ('%d','%d','%s','%s','%s', '%s','%s')",
            // di.status,di.totalSize,di.thumbUrl,di.fileLinkurl,di.fileName,
            // di.fileId,di.duration);
            // MyUtils.showLog(sql);//ft_4.3
            // boolean result =
            // false;//TzzxDB.getInstance().execSQL(sql);//ft_4.3
            // 设置保存路径
            if ("".equals(StringUtil.StrTrim(info.saveFilePath)))
                info.saveFilePath = calcSaveFilePath("apk", info.packageName);// 初始化下载地址
//            result = ZeroVideoDBUtil.addVideoInfo(context, info);
            // if(result){
            if(!isRepeatDownload(info)){
                downloadList.put(info.getPackageName(), info);
             }
//            downloadList.add(info);
            // }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // /**
    // * 更新下载文件信息到数据库
    // * @param di
    // * @return
    // */
    // private static boolean updateDBDownloadTask(DownloadInfo di){
    // if(di == null )
    // return false;
    //
    // // String sqlstr =
    // "update downloadtask set status='%d',totalsize='%d',thumburl='%s'," +
    // // " filelinkurl='%s',filename='%s',savefilepath='%s',currsize='%d' " +
    // // " where fileid='%s'";
    // // String sql = String.format(sqlstr, di.status,di.totalSize,di.thumbUrl,
    // // di.fileLinkurl,di.fileName,di.saveFilePath, di.currSize, di.fileId);
    // //
    // // MyUtils.showLog(di.saveFilePath+"---"+di.currSize);//ft_4.3
    // ZeroVideoDBUtil.updateVideo(context, videoInfo);
    // return false;//TzzxDB.getInstance().execSQL(sql);//ft_4.3
    // }

    /**
     * 判断是否是重复下载
     * 
     * @return
     */
    public static boolean isRepeatDownload(RecommendAppInfo info) {
        // return downloadList.containsKey(StringUtil.StrTrim(videInfo.aid));
        return downloadList.containsKey(info.getPackageName());
    }

    static public class OnClickListenerEx implements OnClickListener {
        // private AdapterReloader adapter;//ft_4.3
        // public Handler handler;
        //
        // public AdapterReloader getAdapter() {
        // return adapter;
        // }
        //
        // public void setAdapter(AdapterReloader adapter, Handler handler) {
        // this.adapter = adapter;
        // this.handler = handler;
        // }//ft_4.3

        @Override
        public void onClick(View arg0) {
            // if (adapter != null)//ft_4.3
            // adapter.onReload();//ft_4.3
        }
    }

    // /**
    // * 取消下载侦听
    // */
    // static public OnClickListenerEx mCancelListener = new OnClickListenerEx()
    // {
    //
    // @Override
    // public void onClick(View v) {
    // DownloadInfo download = (DownloadInfo) v.getTag(v.getId());
    // if (download == null || TextUtils.isEmpty(download.fileId))
    // return;
    // // download.mHandler = handler;//ft_4.3
    // DownloadInfo entity = DownloadUtil.downloadList.get(download.fileId);
    // if (entity == null)
    // return;
    // // entity.mHandler = handler;//ft_4.3
    // entity.status = DownloadInfo.STATUS_DELETE;
    // if (entity.runnable != null) {
    // entity.runnable.isStop = true;
    // }
    //
    // // 删除下载文件
    // if (!TextUtils.isEmpty(entity.saveFilePath)) {
    // File file = new File(entity.saveFilePath);
    // if (file.exists()) {
    // file.delete();
    // }
    // }
    //
    // //数据库删除
    // if(deleteDBDownloadTask(entity)){
    // downloadList.remove(entity.fileId);
    // }
    //
    // sendToOuterHandler(download, false);
    // super.onClick(v);
    // }
    // };
    //
    // /**
    // * 删除已下载文件侦听
    // */
    // static public OnClickListenerEx mDeleteListener = new OnClickListenerEx()
    // {
    //
    // @Override
    // public void onClick(View v) {
    // DownloadInfo download = (DownloadInfo) v.getTag(v.getId());
    // if (download == null || TextUtils.isEmpty(download.fileId))
    // return;
    // // download.mHandler = handler;//ft_4.3
    // DownloadInfo entity = DownloadUtil.downloadList.get(download.fileId);
    // if (entity == null)
    // return;
    // // entity.mHandler = handler;//ft_4.3
    //
    // // 删除下载文件
    // if (!TextUtils.isEmpty(entity.saveFilePath)) {
    // File file = new File(entity.saveFilePath);
    // if (file.exists()) {
    // file.delete();
    // }
    // }
    //
    // //数据库删除
    // if(deleteDBDownloadTask(entity)){
    // downloadList.remove(entity.fileId);
    // }
    //
    // sendToOuterHandler(download, false);
    // super.onClick(v);
    // }
    // };
    //
//    /**
//     * 下载侦听器
//     */
//    static public OnClickListenerEx mDownListener = new OnClickListenerEx() {
//        @Override
//        public void onClick(View v) {
//            // TODO 下载侦听器
//            RecommendAppInfo download = (RecommendAppInfo) v.getTag(v.getId());
//            if (download == null || TextUtils.isEmpty(download.packageName))
//                return;
//            // download.mHandler = handler;//ft_4.3
//            DownloadAppUtil.startDownThread(context, download, outerHandler,);
//
//            super.onClick(v);
//        }
//    };

//    /**
//     * 停止下载侦听
//     */
//    static public OnClickListenerEx mStopListener = new OnClickListenerEx() {
//
//        @Override
//        public void onClick(View v) {
//            RecommendAppInfo download = (RecommendAppInfo) v.getTag(v.getId());
//            if (download == null || TextUtils.isEmpty(download.packageName))
//                return;
//            // download.mHandler = handler;//ft_4.3
//            // RecommendAppInfo entity = downloadList.get(download.packageName);
//            // RecommendAppInfo entity = downloadList.ge
//            // if (entity == null)
//            // return;
//            // entity.mHandler = handler;//ft_4.3
//            download.status = RecommendAppInfo.STATUS_STOP;
//            if (download.runnable != null) {
//                download.runnable.isStop = true;
//            }
//            super.onClick(v);
//        }
//    };
    
    public static void stopDownLoad(RecommendAppInfo info){
        if(info == null){
            return;
        }
        if(TextUtils.isEmpty(info.getPackageName())){
            return;
        }
        RecommendAppInfo app = downloadList.get(info.getPackageName());
        if(app == null){
            return;
        }
        if (app.runnable != null) {            
//            if(!app.runnable.isStop){
                app.runnable.isStop = true;
//                app.status = RecommendAppInfo.STATUS_STOP;
//            }
        }
    }
    

    /**
     * @param title
     * @param key
     * @param size
     * @param fileId
     * @param thumburl
     * @param filepath
     */
    public static boolean startDownThread(Context context, RecommendAppInfo appInfo, Handler handler,int pos) {
        
        if (TextUtils.isEmpty(appInfo.packageName)) {
            Toast.makeText(context, "网络请求异常，请稍后再试！", Toast.LENGTH_SHORT).show();
            if(outerHandler != null){
                Message message = outerHandler.obtainMessage();
                message.what = RecommendAppInfo.STATUS_STOP;
                message.arg1 = pos;
                sendToOuterHandler(message);
            }
            return false;
        }
        DownloadAppUtil.context = context;
        Logger.i(TAG, "startDownThread_downloadList.size==" + downloadList.size());
        // 设置保存路径
        if ("".equals(StringUtil.StrTrim(appInfo.saveFilePath)))
            appInfo.saveFilePath = calcSaveFilePath("apk", appInfo.packageName);// 初始化下载地址
        
        // 判断在无sdcard的时候可用内存是否足够下载
        if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
                .getExternalStorageState())) {

            // 获取内部存储空间
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            long storesize = availableBlocks * blockSize;
            // /
            long size = appInfo.currSize;
            if (size + 10 * 1024 * 1024 >= storesize) {
                Toast.makeText(context, "当前可用存储空间不足，下载失败！", Toast.LENGTH_SHORT).show();
                if(outerHandler != null){
                    Message message = outerHandler.obtainMessage();
                    message.what = RecommendAppInfo.STATUS_STOP;
                    message.arg1 = pos;
                    sendToOuterHandler(message);
                }
                return false;
            }
        }
        
        if(!isRepeatDownload(appInfo)){
            downloadList.put(appInfo.packageName, appInfo);
            appInfo.status = RecommendAppInfo.STATUS_DOWNNING;
            Logger.i(TAG, "start_downhread_下来就要开启线程 了");
            appInfo.totalSize = 0;
            appInfo.mHandler = handler;
            if(outerHandler != null){
                Message message = outerHandler.obtainMessage();
                message.what = RecommendAppInfo.STATUS_DOWNNING;
                message.arg1 = pos;
                message.arg2 = appInfo.progress;
                sendToOuterHandler(message);
            }
            
            // 发出通知
            // updateNotificationManager.notify(entity.id,
            // entity.updateNotification);
            // 开启一个新的线程下载，如果使用Service同步下载，会导致ANR问题，Service本身也会阻塞
            if (appInfo.runnable != null) {
                appInfo.runnable.isStop = true;
            }
            appInfo.runnable = new DownAppRunnable(context, appInfo,pos);
            Thread thread = new Thread(appInfo.runnable);
            thread.start();
        }else{
            RecommendAppInfo app = downloadList.get(appInfo.getPackageName());
            app.status = RecommendAppInfo.STATUS_DOWNNING;
            Logger.i(TAG, "start_downhread_下来就要开启线程 了");
            app.totalSize = 0;
            app.mHandler = handler;
            app.progress = appInfo.progress;
            if(outerHandler != null){
                Message message = outerHandler.obtainMessage();
                message.what = RecommendAppInfo.STATUS_DOWNNING;
                message.arg1 = pos;
                message.arg2 = app.progress;
                sendToOuterHandler(message);
            }
            // 发出通知
            // updateNotificationManager.notify(entity.id,
            // entity.updateNotification);
            // 开启一个新的线程下载，如果使用Service同步下载，会导致ANR问题，Service本身也会阻塞
            if (app.runnable != null) {
                app.runnable.isStop = true;
            }
            app.runnable = new DownAppRunnable(context, app,pos);
            Thread thread = new Thread(app.runnable);
            thread.start();
        }
        
        return true;
    }

    /**
     * 根据linkurl算下载保存路径
     * 
     * @param fileLinkurl
     * @return
     */
    public static String calcSaveFilePath(String exName, String fileId) {
        String result = "";
        if (!TextUtils.isEmpty(exName)) {
            File file = new File(DOWNLOADDIR);
            if (!file.exists()) {
                file.mkdirs();
            }

            // result = DOWNLOADDIR +"/"+ StringUtil.MD5Encode(fileLinkurl) +
            // "." + StringUtil.getFileExtName(fileLinkurl);
            result = DOWNLOADDIR + "/" + fileId + "." + exName;
        }

        return result;
    }
    
    /** 
     * 安装APK文件 
     */  
    public static void installApk(Context context,String fileName)  
    {  
//        File apkfile = new File(DOWNLOADDIR, fileName);  
        File apkfile = new File(fileName);  
        if (!apkfile.exists())
        {  
            return;  
        }  
        Intent i = new Intent(Intent.ACTION_VIEW);  
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");  
        context.startActivity(i);  
//        sendOutMsg(GO_INSTALL);
    }   

    public static int isExist(RecommendInfoApp info){
        int type = 0;//0不存在，1存在部分 2已下载完成
        try{
            File dir = new File(DOWNLOADDIR);
            if(!dir.exists()){
                return 0;
            }
            File file = new File(info.saveFilePath);
            if(!file.exists()){
                return 0;
            }
            Logger.i(TAG, "file.length()=="+file.length());
            Logger.i(TAG, "info.totalSize=="+info.totalSize);
            if(file.length() >= info.totalSize && info.totalSize > 0){
                return 2;
            }
            return 1;
        }catch(Exception e){
            
        }
        return type;
    }
    
    public static int isExist(RecommendAppInfo info){
        int type = 0;//0不存在，1存在部分 2已下载完成
        try{
            File dir = new File(DOWNLOADDIR);
            if(!dir.exists()){
                return 0;
            }
            File file = new File(info.saveFilePath);
            if(!file.exists()){
                return 0;
            }
            Logger.i(TAG, "file.length()111=="+file.length());
            Logger.i(TAG, "info.totalSize1111=="+info.totalSize);
            if(file.length() >= info.totalSize && info.totalSize > 0){
                return 2;
            }
            return 1;
        }catch(Exception e){
            
        }
        return type;
    }
}
